<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="模板名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入模板名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="模板类型" prop="type">
        <el-select style="width: 100%" v-model="queryParams.type" placeholder="请选择模板类型" clearable>
          <el-option
            v-for="dict in dict.type.wms_custom_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select style="width: 100%" v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.wms_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['wms:custom:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wms:custom:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wms:custom:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wms:custom:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="customList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="" align="center" prop="id"/>
      <el-table-column label="模板名称" align="center" prop="name"/>
      <el-table-column label="模板类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wms_custom_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wms_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wms:custom:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wms:custom:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改自定义模板对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入模板名称"/>
        </el-form-item>
        <el-form-item label="模板类型" prop="type">
          <el-select style="width: 100%" v-model="form.type" placeholder="请选择模板类型">
            <el-option
              v-for="dict in dict.type.wms_custom_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.wms_status"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
        <el-divider content-position="center">自定义信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleFieldAdd">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button :disabled="!!form.id" type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteField">
              删除
            </el-button>
          </el-col>
        </el-row>
        <el-table :data="fieldList" :row-class-name="rowFieldIndex"
                  @selection-change="handleFieldSelectionChange" ref="wmsGoods">
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="标题" prop="label" width="150"/>
          <el-table-column label="属性名字" prop="prop" width="150"/>
          <el-table-column label="表单类型" prop="name" width="150">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.wms_form_type" :value="scope.row.type"/>
            </template>
          </el-table-column>
          <el-table-column label="默认值" prop="value" width="150"/>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 添加或修改自定义字段对话框 -->
    <el-dialog :title="fieldTitle" :visible.sync="fieldOpen" append-to-body>
      <el-form ref="fieldForm" :model="fieldForm" :rules="fieldRules" label-width="120px">
        <el-form-item label="标题" prop="label">
          <el-input v-model="fieldForm.label" placeholder="请输入标题"/>
        </el-form-item>
        <el-form-item label="属性名称" prop="prop">
          <el-input v-model="fieldForm.prop" placeholder="请输入属性名称"/>
        </el-form-item>
        <el-form-item label="表单类型" prop="type">
          <el-select
            style="width: 100%"
            v-model="fieldForm.type"
            placeholder="请选择表单类型">
            <el-option
              v-for="dict in dict.type.wms_form_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设置" prop="required">
          <el-checkbox v-model="fieldForm.required">必填</el-checkbox>
          <el-checkbox v-model="fieldForm.readOnly">只读</el-checkbox>
        </el-form-item>
        <el-form-item v-if="fieldForm.type!=2&&fieldForm.type!=3" label="最小(长度/范围)" prop="min">
          <el-input v-model="fieldForm.min" placeholder="请输入属性名称"/>
        </el-form-item>
        <el-form-item v-if="fieldForm.type!=2&&fieldForm.type!=3" label="最大(长度/范围)" prop="max">
          <el-input v-model="fieldForm.max" placeholder="请输入属性名称"/>
        </el-form-item>
        <el-form-item v-if="fieldForm.type!=1&&fieldForm.type!=2&&fieldForm.type!=3" label="精度" prop="decimalPrecision">
          <el-input v-model="fieldForm.decimalPrecision" placeholder="请输入精度"/>
        </el-form-item>
        <el-form-item label="默认值" prop="value">
          <el-input v-model="fieldForm.value" placeholder="请输入默认值"/>
        </el-form-item>
        <div v-if="fieldForm.type==2">
          <el-divider content-position="center">选项</el-divider>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleOptionAdd">添加</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteOption">删除</el-button>
            </el-col>
          </el-row>
          <el-table :data="fieldForm.option" :row-class-name="rowOptionIndex"
                    @selection-change="handleOptionSelectionChange" ref="wmsGoods">
            <el-table-column type="selection" width="50" align="center"/>
            <el-table-column label="序号" align="center" prop="index" width="50"/>
            <el-table-column label="标题" prop="label">
              <template slot-scope="scope">
                <el-input v-model="scope.row.label" placeholder="请输入标题"/>
              </template>
            </el-table-column>
            <el-table-column label="值" prop="value">
              <template slot-scope="scope">
                <el-input v-model="scope.row.value" placeholder="请输入标题"/>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFieldForm">确 定</el-button>
        <el-button @click="fieldCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listCustom, getCustom, delCustom, addCustom, updateCustom} from "@/api/wms/custom";

export default {
  name: "Custom",
  dicts: ['wms_status', 'wms_custom_type', 'wms_form_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedWmsGoods: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 自定义模板表格数据
      customList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        type: null,
        context: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          {required: true, message: "模板名称不能为空", trigger: "blur"}
        ],
        type: [
          {required: true, message: "模板类型不能为空", trigger: "blur"}
        ],
      },
      //-------------
      fieldTitle: "",
      fieldOpen: false,
      fieldForm: {},
      fieldRules: {
        label: [
          {required: true, message: "标题不能为空", trigger: "blur"}
        ],
        prop: [
          {required: true, message: "属性名不能为空", trigger: "blur"}
        ],
        type: [
          {required: true, message: "类型不能为空", trigger: "blur"}
        ]
      },
      checkedOption: [],
      //--------------
      fieldList: [],
      checkedField: []
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleDeleteOption() {
      if (this.checkedOption.length == 0) {
        this.$modal.msgError("请先选择要删除的数据");
      } else {
        const fieldForm = this.fieldForm.option;
        const checkedOption = this.checkedOption;
        this.fieldForm.option = fieldForm.filter(function (item) {
          return checkedOption.indexOf(item.index) == -1
        });
      }
    },
    handleOptionAdd() {
      let obj = {};
      obj.leabl = "";
      obj.value = "";
      this.fieldForm.option.push(obj);
    },
    handleOptionSelectionChange(selection) {
      this.checkedOption = selection.map(item => item.index)
    },
    rowOptionIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    //=============================
    rowFieldIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    handleFieldSelectionChange(selection) {
      this.checkedField = selection.map(item => item.index)
    },
    /** 新增字段按钮操作 */
    handleFieldAdd() {
      this.fieldReset();
      this.fieldOpen = true;
      this.fieldTitle = "添加字段";
    },
    handleDeleteField() {
      if (this.checkedField.length == 0) {
        this.$modal.msgError("请先选择要删除的数据");
      } else {
        const fieldList = this.fieldList;
        const checkedField = this.checkedField;
        this.fieldList = fieldList.filter(function (item) {
          return checkedField.indexOf(item.index) == -1
        });
      }
    },
    submitFieldForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.fieldList.push({...this.fieldForm});
          this.fieldCancel();
        }
      });
    },
    fieldCancel() {
      this.fieldOpen = false;
      this.fieldReset();
    },
    fieldReset() {
      this.fieldForm = {
        label: null,
        prop: null,
        type: null,
        required: false,
        min: null,
        max: null,
        decimalPrecision: null,
        value: null,
        readOnly: false,
        option: [
          // {
          //   label: null,
          //   value: null,
          // }
        ]
      };
      this.resetForm("fieldForm");
    },
    /** 查询自定义模板列表 */
    getList() {
      this.loading = true;
      listCustom(this.queryParams).then(response => {
        this.customList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        type: null,
        context: null,
        status: "0",
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.fieldList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加自定义模板";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCustom(id).then(response => {
        this.form = response.data;
        this.fieldList = JSON.parse(this.form.context)
        this.open = true;
        this.title = "修改自定义模板";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.context = JSON.stringify(this.fieldList);
          if (this.form.id != null) {
            updateCustom(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCustom(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除自定义模板编号为"' + ids + '"的数据项？').then(function () {
        return delCustom(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wms/custom/export', {
        ...this.queryParams
      }, `custom_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
